//
//  HttpTool.m
//  AI
//
//  Created by 甘世清 on 2023/7/15.
//

#import "HttpTool.h"
#import "LoginViewController.h"
#import <XYUUID/XYUUID.h>
#import "VipView.h"
#import "MeVipViewController.h"
@implementation HttpTool
static HttpTool* tool;
+(HttpTool*)shareMZHttpTool{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[HttpTool alloc]init];

    });
    return tool;
}

/// get请求
/// @param urlString url
/// @param parameters 参数
/// @param successBlock  成功返回
/// @param failBlock 失败的返回
+(void)SQ_get:(NSString*)urlString ParamDic:(NSMutableDictionary*)parameters successBlock:(httpSuccessBlock)successBlock andFailBloc:(httpFailBlock)failBlock
{
    //上传 json
    [self shareMZHttpTool].httpManger.requestSerializer = [AFJSONRequestSerializer serializer];
    [[self shareMZHttpTool].httpManger GET:urlString parameters:parameters headers:[self SQ_getHeaderData]  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self MZ_AnalysizeObject:responseObject successBlock:successBlock andFailBloc:failBlock];
        NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)[task response];
        DTLog(@"\n\n->接口请求返回结果: %@\n源请求url: %@\n 请求参数:%@\n 返回code码:%ld",responseObject,task.originalRequest.URL.absoluteString,parameters,(long)httpResponse.statusCode);
     }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [self MZ_Error:error parameters:parameters urlstring:urlString andFailBloc:failBlock];
     }];
}



/// post请求
/// @param urlString url
/// @param parameters 参数
/// @param successBlock 成功的返回
/// @param failBlock 失败的返回
+(void)post:(NSString*)urlString paramDic:(NSMutableDictionary*)parameters  successBlock:(httpSuccessBlock)successBlock andFailBloc:(httpFailBlock)failBlock
{
    [self shareMZHttpTool].httpManger.requestSerializer = [AFHTTPRequestSerializer serializer];
    [[self shareMZHttpTool].httpManger POST:urlString parameters:parameters headers:[self SQ_getHeaderData]  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self MZ_AnalysizeObject:responseObject successBlock:successBlock andFailBloc:failBlock];
        NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)[task response];
        DTLog(@"\n\n->接口请求返回结果: %@\n源请求url: %@\n 请求参数:%@\n 返回code码:%ld",responseObject,task.originalRequest.URL.absoluteString,parameters,(long)httpResponse.statusCode);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          [self MZ_Error:error parameters:parameters urlstring:urlString andFailBloc:failBlock];
    }];
    
}
/// post请求
/// @param urlString url
/// @param parameters 参数
/// @param successBlock 成功的返回
/// @param failBlock 失败的返回
+(void)postJson:(NSString*)urlString paramDic:(NSMutableDictionary*)parameters  successBlock:(httpSuccessBlock)successBlock andFailBloc:(httpFailBlock)failBlock
{
    //上传 json
    [self shareMZHttpTool].httpManger.requestSerializer = [AFJSONRequestSerializer serializer];
    [[self shareMZHttpTool].httpManger POST:urlString parameters:parameters headers:[self SQ_getHeaderData] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        [self MZ_AnalysizeObject:responseObject successBlock:successBlock andFailBloc:failBlock];
        NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)[task response];
        DTLog(@"\n\n->接口请求返回结果: %@\n源请求url: %@\n 请求参数:%@\n 返回code码:%ld",responseObject,task.originalRequest.URL.absoluteString,parameters,(long)httpResponse.statusCode);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self MZ_Error:error parameters:parameters urlstring:urlString andFailBloc:failBlock];
    }];
}

/// 上传图片
/// @param image 图片
/// @param successBlock 成功回调
/// @param failBlock 失败回调
+(void)SQ_Image:(UIImage*)image successBlock:(httpSuccessBlock)successBlock andFailBloc:(httpFailBlock)failBlock{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSData * data = UIImageJPEGRepresentation(image,0.5);
    [[self shareMZHttpTool].httpManger POST:@"upload/upload" parameters:dic headers:[self SQ_getHeaderData] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName = [NSString  stringWithFormat:@"%@.png", [self currentTime]];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"multipart/form-data"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BaseModel *  model = [BaseModel mj_objectWithKeyValues:responseObject];
        model.responseObject = [[NSDictionary alloc]initWithDictionary:responseObject];
        [self MZ_AnalysizeObject:responseObject successBlock:successBlock andFailBloc:failBlock];
        NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)[task response];
        DTLog(@"\n\n->接口请求返回结果: %@\n源请求url: %@\n  返回code码:%ld",responseObject,httpResponse.URL.absoluteString,(long)httpResponse.statusCode);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self MZ_Error:error parameters:nil urlstring:@"upload" andFailBloc:failBlock];
    }];
    
    
}


 

//处理请求成功
+(void)MZ_AnalysizeObject:(id)responseObject successBlock:(httpSuccessBlock)successBlock andFailBloc:(httpFailBlock)failBlock{
    [YJProgressHUD hide];
    BaseModel *  model = [BaseModel mj_objectWithKeyValues:responseObject];
    model.responseObject = [[NSDictionary alloc]initWithDictionary:responseObject];
 
//    DTLog(@"json:%@",[model.data mj_JSONString]);
    if (model.message.length <=0 ) {
        model.message= @"请求失败";
    }
    if (model.code == 0) {
        if (successBlock) {
            successBlock(model);
        }
    }else{
        if (failBlock) {
            failBlock(model,nil);
        }
        if (model.code == -1){
            [UserModel clearLocalUserModel];
            LoginViewController * vc = [[LoginViewController alloc]init];
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
            [[[[UIApplication sharedApplication] windows]firstObject] setRootViewController:nav];
        }
        if (model.code == -3) {
            UserModel * mo = [UserModel share];
            mo.isVip = NO;
            [UserModel updateLocalUserModel:mo];
            [self pushVIPAlert];
        }
    }
}
+(NSMutableDictionary*)SQ_getHeaderData{
    NSString * token = [UserModel share].token;
   NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    if (token.length >0) {
        [dic setObject:token forKey:@"token"];
    }
    NSString * language = [NSLocale preferredLanguages].firstObject;
    if ([language isEqualToString:@"zh-Hant-TW"]) {
        //台湾
        [dic setObject:@"2" forKey:@"language"];
    } else  if ([language isEqualToString:@"zh-Hant-HK"])  {
        [dic setObject:@"1" forKey:@"language"];
    }else{
        [dic setObject:@"0" forKey:@"language"];
    }
    [dic setObject:[XYUUID uuidForDevice] forKey:@"info"];
    DTLog(@"header的数据----%@",dic);
    return dic;
}

//处理失败请求
+(void)MZ_Error:(NSError*)error  parameters:(NSMutableDictionary*)parameters urlstring:(NSString*)urlString andFailBloc:(httpFailBlock)failBlock{

    BaseModel *  model  = [BaseModel new];
    model.code = error.code;
    model.error = error;
    model.message = @"请求失败";
    failBlock(model,error);
    NSInteger codeint  = error.code;
    DTLog(@"---接口报错----\n接口名称:%@ \n请求参数: %@-报错信息:%@--错误码:%ld",urlString,parameters,error.userInfo,(long)codeint);
    //如果token失败
    if (model.code == -1){
        [UserModel clearLocalUserModel];
        LoginViewController * vc = [[LoginViewController alloc]init];
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
        [[[[UIApplication sharedApplication] windows]firstObject] setRootViewController:nav];
    }
    if (model.code == -3) {
        [self pushVIPAlert];
    }
}


+(void)pushVIPAlert{
    
        VipView * view = [[VipView alloc]init];
        view.frame = CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT);
        LSTPopView * pop = [LSTPopView initWithCustomView:view
                                               parentView:nil
                                                 popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
        pop.hemStyle = LSTHemStyleCenter;
        [pop pop];
        LSTPopViewWK(pop)
        [pop setBgClickBlock:^{
            [wk_pop dismiss];
        }];
       
        [view setOpenVIPBlock:^{
            [wk_pop dismiss];
            MeVipViewController  * vc = [[MeVipViewController alloc]init];
            [[Manager SQ_getCurrentViewController].navigationController pushViewController:vc animated:YES];
        }];
        [view setCloseViewBlock:^{
            [wk_pop dismiss];
        }];
}

 

/**
 数据请求的工具
 
 @return 返回数据请求的工具
 */
-(AFHTTPSessionManager *)httpManger{

    if (_httpManger == nil) {
         NSURLSessionConfiguration *sessionconfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        sessionconfig.timeoutIntervalForRequest = 30;
            NSURL *baseUrl =[NSURL URLWithString:BaseUrl] ;
//            baseUrl = [NSURL URLWithString:BaseUrl] ;
            _httpManger  = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl sessionConfiguration:sessionconfig];
        
            [_httpManger.requestSerializer willChangeValueForKey:@"timeoutInterval"];

            _httpManger.requestSerializer.timeoutInterval = 15.0;
        // 是否允许无效证书, 默认为NO
            _httpManger.securityPolicy.allowInvalidCertificates = YES;
           // 是否校验域名, 默认为YES
            _httpManger.securityPolicy.validatesDomainName = NO;
            // 设置请求头
 
            // 返回的是json的字符串
            _httpManger.responseSerializer = [AFJSONResponseSerializer serializer];
            _httpManger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
         
    }
 
    return _httpManger;
}


+ (NSString *_Nullable)currentTime {
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time = [date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time * 1000];
    return timeString;
}
@end
